<template>
  <div class="subject-report">
    <div class="header">
      <img
        src="@/assets/images/back_arrow.png"
        class="back"
        alt="header"
        @click="goBack"
      />
    </div>
    <div class="main">
      <section class="desc-box" v-loading="descLoading">
        <DescItem
          v-for="(item, index) in description"
          :key="index"
          :item="item"
        ></DescItem>
      </section>
      <section class="recommend-box">
        <div class="recommend-title">推荐专业</div>
        <div class="recommend-list">
          <MajorCard
            class="major-item"
            v-for="(item, index) in majorList"
            :item="item"
            :key="index"
            @click="goToMajorDetail(item)"
          >
          </MajorCard>
        </div>
      </section>
      <section class="recommend-box">
        <div class="recommend-title">推荐院校</div>
        <div class="recommend-list">
          <SchoolCard
            class="major-item"
            v-for="(item, index) in schoolList"
            :item="item"
            :key="index"
            @click="goToSchoolDetail(item)"
          >
          </SchoolCard>
        </div>
      </section>
      <section class="can-select-box">
        <div class="item" v-for="item in canSelectDataList" :key="item.title">
          <span class="label">{{ item.title }}：</span>
          <span class="value"
            >本科{{ item.bachelor }} / 专科{{ item.associate }} / 总数{{
              item.total
            }}</span
          >
        </div>
      </section>
      <section class="chart-section">
        <div class="title">6类院校地区数量详情</div>
        <BarChart :data="schoolData" labelColor="" yAxisName="(院校数量)" />
      </section>
      <section class="chart-section">
        <div class="title">可报考专业院校分布 top10</div>
        <BarChart
          :data="majorData"
          labelColor="#0169FF"
          colorFrom="#589BFD"
          colorTo="#BBDEFF"
          yAxisName="(院校数量)"
        />
      </section>
      <section class="chart-section">
        <CollegeTable
          labelColor="#0169FF"
          colorFrom="#589BFD"
          colorTo="#BBDEFF"
        ></CollegeTable>
      </section>
    </div>
  </div>
</template>
<script setup>
import {
  ref,
  onBeforeMount,
  computed,
  defineAsyncComponent,
  onMounted,
} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useSubjectSelectStore } from '@/store/subjectSelect';
import { onBackPressed } from '@/utils/androidFn.js';
import { formatData } from '@/utils/subjectData';
import {
  selectComboProfile,
  getSubjectInfo,
  selectList,
} from '@/api/subjectSelect.js';

const DescItem = defineAsyncComponent(() =>
  import('@/components/DescItem.vue')
);
const MajorCard = defineAsyncComponent(() =>
  import('./components/MajorCard.vue')
);
const SchoolCard = defineAsyncComponent(() =>
  import('./components/SchoolCard.vue')
);
const BarChart = defineAsyncComponent(() =>
  import('@/components/BarChart.vue')
);
const CollegeTable = defineAsyncComponent(() =>
  import('./components/CollegeTable.vue')
);

const route = useRoute();
const router = useRouter();
const goBack = () => {
  if (route.query?.fromType == 'android') {
    onBackPressed(router);
  } else {
    router.go(-1);
  }
};

const store = useSubjectSelectStore();

const subjectList = computed(() => store.homeData.subjectList);
const province = computed(() => store.homeData.province);

// 页面挂载前判断 subjectList 是否存在，不存在则返回 subjectSelect 页面
onBeforeMount(() => {
  if (!subjectList.value || subjectList.value.length === 0) {
    router.replace({ name: 'SubjectSelect' });
  }
});

const searchAllowSubject = ref(
  subjectList.value.map((item) => {
    return item.id;
  })
);

const descLoading = ref(false);
const description = ref([]);
const selectComboProfileFn = async () => {
  descLoading.value = true;
  console.log('province1111', province.value);

  try {
    const params = {
      searchAllowSubject: searchAllowSubject.value.join(','),
      localRegionId: province.value.regionId,
    };
    const res = await selectComboProfile(params);
    descLoading.value = false;
    if (res.code == 200) {
      description.value = res.data;
    }
  } catch (error) {
    descLoading.value = false;
    console.log(error);
  }
};

const subjectId = ref('');
const getSubjectInfoFn = async () => {
  try {
    const params = {
      searchAllowSubjectList: [searchAllowSubject.value.join(',')],
      limitType: province.value.regionName == '北京' ? 3 : 1,
    };
    const res = await getSubjectInfo(params);
    if (res.code == 200) {
      subjectId.value = res.data[0].subjectId;
    }
  } catch (error) {
    console.log(error);
  }
};

const schoolData = ref([]);
const majorData = ref([]);
const majorList = ref([]);
const schoolList = ref([]);
const canSelectDataList = ref([]);
const selectListFn = async (categoryKey) => {
  try {
    const params = {
      regionId: province.value.regionId,
      recordYear: province.value.defaultYear,
      subjectId: subjectId.value,
      categoryKey,
    };
    const res = await selectList(params);
    if (res.code == 200 && res.data.length) {
      switch (categoryKey) {
        case 'top10AvailablePro': // 可报考专业前10
          majorData.value = formatData(res.data[0]?.dataContent, 'value');
          break;
        case 'regionCollegeCount': // 院校地区数量详情
          schoolData.value = formatData(res.data[0]?.dataContent, 'value');
          break;
        case 'recommendSubjectPro': // 推荐选课关联专业
          majorList.value = JSON.parse(res.data[0]?.dataContent) || [];
          break;
        case 'recommendSubjectCollege': // 推荐选课关联学校
          schoolList.value = JSON.parse(res.data[0]?.dataContent) || [];
          break;
        case 'admissibleCollegeData': // 可选院校/专业/招生人数
          canSelectDataList.value = transformData(res.data[0]?.dataContent);
          break;
        default:
          break;
      }
    }
  } catch (error) {
    console.log(error);
  }
};

function transformData(originalData) {
  const arr = JSON.parse(originalData);
  if (!Array.isArray(arr)) return [];
  const resultMap = new Map();

  arr.forEach((item) => {
    const { showName, cateType, value } = item;

    if (!resultMap.has(showName)) {
      resultMap.set(showName, {
        title: showName,
        total: 0,
        associate: 0,
        bachelor: 0,
      });
    }

    const category = resultMap.get(showName);
    switch (cateType) {
      case '0':
        category.total = value;
        break;
      case '10':
        category.associate = value;
        break;
      case '30':
        category.bachelor = value;
        break;
    }
  });

  return Array.from(resultMap.values());
}

const goToMajorDetail = (item) => {
  router.push({
    name: 'MajorDetail',
    query: {
      positionTagId: item.positionTagId,
      tagName: item.showName,
      cateType: item.cateType,
    },
  });
};

const goToSchoolDetail = (item) => {
  router.push({
    name: 'SchoolDetail',
    query: {
      dataId: item.collegeId,
      dataName: item.showName,
    },
  });
};

onMounted(async () => {
  selectComboProfileFn();
  await getSubjectInfoFn();
  selectListFn('top10AvailablePro');
  selectListFn('regionCollegeCount');
  selectListFn('recommendSubjectPro');
  selectListFn('recommendSubjectCollege');
  selectListFn('admissibleCollegeData');
});
</script>

<style scoped lang="scss">
.subject-report {
  height: 100vh;
  background: url('@/assets/images/homeBg.png') no-repeat center center;
  background-size: 100% 100%;
  padding: 0 60px 60px 60px;
  box-sizing: border-box;
  overflow: hidden;
  .header {
    padding: 20px 0;
    .back {
      width: 48px;
      height: 48px;
    }
  }
  .main {
    height: calc(100vh - 88px);
    box-sizing: border-box;
    padding: 40px 40px 0 40px;
    background-color: #fff;
    border-radius: 32px 32px 20px 20px;
    overflow-y: auto;
    .desc-box {
      display: grid;
      min-height: 70vh; // loading的高度
      grid-template-columns: repeat(2, 1fr);
      gap: 20px 44px;
      :deep(.content) {
        height: calc(100% - 140px);
      }
    }
    .recommend-box {
      margin-top: 60px;
      .recommend-title {
        text-align: center;
        font-weight: bold;
        font-size: 34px;
        color: #333333;
        line-height: 48px;
        margin-bottom: 23px;
      }
      .recommend-list {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 24px;
      }
    }
    .can-select-box {
      margin-top: 24px;
      display: flex;
      flex-wrap: wrap;
      gap: 66px;
      padding: 58px 32px;
      background: #f5f7fa;
      border-radius: 8px;
      font-size: 26px;
      .item {
        .label {
          color: #333;
          font-weight: bold;
        }
        .value {
          color: #555;
        }
      }
    }
    .chart-section {
      width: 100%;
      height: 480px;
      margin-top: 80px;
      .title {
        text-align: center;
        font-weight: bold;
        font-size: 34px;
        color: #333333;
        line-height: 48px;
      }
    }
  }
}
</style>
